package org.hongbo.springbootebsapi.handler;


import org.hongbo.springbootebsapi.annotations.ResponseResult;
import org.hongbo.springbootebsapi.interceptor.ResponseResultInterceptor;
import org.hongbo.springbootebsapi.jwt.JwtTokenUtil;
import org.hongbo.springbootebsapi.result.DefaultErrorResult;
import org.hongbo.springbootebsapi.result.PlatformResult;
import org.hongbo.springbootebsapi.result.Result;
import org.hongbo.springbootebsapi.util.JsonUtil;
import org.hongbo.springbootebsapi.util.RequestContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @desc 接口响应体处理器
 * 
 * @author zhumaer
 * @since 4/1/2018 3:00 PM
 */
@ControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {

	@Autowired
	private JwtTokenUtil jwtTokenUtil;

	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		ResponseResult responseResultAnn = (ResponseResult) RequestContextUtil.getRequest().getAttribute(ResponseResultInterceptor.RESPONSE_RESULT);
		return responseResultAnn == null ? false : true;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
		ResponseResult responseResultAnn = (ResponseResult) RequestContextUtil.getRequest().getAttribute(ResponseResultInterceptor.RESPONSE_RESULT);

		Class<? extends Result> resultClazz = responseResultAnn.value();

		if (resultClazz.isAssignableFrom(PlatformResult.class)) {
			if (body instanceof DefaultErrorResult) {
				DefaultErrorResult defaultErrorResult = (DefaultErrorResult) body;
				return PlatformResult.builder()
						.code(defaultErrorResult.getCode())
						.message(defaultErrorResult.getMessage())
						.refreshToken(jwtTokenUtil.getRefreshToken())
						.data(defaultErrorResult.getErrors())
						.build();
			}

			if(body instanceof String){
			    return JsonUtil.object2Json(PlatformResult.success(body));
            }

			return PlatformResult.success(body);
		}

		return body;
	}

}
